import axios from 'axios';
import qs from 'qs';
import { isPlainObject } from 'lodash'
import editor from "../../store/modules/fastposter/editor";
import { Message } from 'element-ui';

let baseURL = process.env.VUE_APP_BASE_URL;
if (baseURL === '/') {
    baseURL = (location.protocol + '//' + location.host + location.pathname).replace(/(.+\/).*$/, '$1')
}
window.API_URL = baseURL;
console.info('baseURL', baseURL)

let baseURL2 = process.env.VUE_APP_BASE_URL2;
if (baseURL2 === '/') {
    baseURL2 = (location.protocol + '//' + location.host + location.pathname).replace(/(.+\/).*$/, '$1')
}
console.info('baseURL2', baseURL2)

const base = process.env.VUE_APP_BASE_URL2
/**
 * 优先使用url 中的token 参数
 * @returns
 */
export function token() {
    const url = window.location.href
    const params = getParams(url)
    return params?.token || localStorage.getItem(process.env.VUE_APP_FP_TOKEN) || '';
}

function getParams(url) {
    const regex = /[?&]([^=#]+)=([^&#]*)/g;
    const params = {};
    let match;
    // eslint-disable-next-line no-cond-assign
    while (match = regex.exec(url)) {
        params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
    }
    return params;
}

const http = axios.create({
    baseURL: baseURL,
    timeout: 3000,
    // headers: {'X-Custom-Header': 'foobar'},
    // withCredentials: true
});


/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
    config.headers['token'] = token();
    
    var defaults = {
        '_t': new Date().getTime()
    };
    if (config.method === 'get') {
        if (isPlainObject(config.params)) {
            config.params = {
                ...defaults,
                ...config.params
            }
        }
    } else if (config.method === 'post') {
        if (isPlainObject(config.data)) {
            config.data = {
                ...defaults,
                ...config.data
            }
        }
        if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
            config.data = qs.stringify(config.data)
        }
    }
    return config
}, error => {
    return Promise.reject(error)
});

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
    if (response.data && response.data.code === 401) { // 401, token失效
        console.warn("没有登录")
        editor.state.showLogin = true;
    } else if (response.data && response.data.code !== 0) {
        Message.warning(response.data.msg)
    }
    return response.data
}, error => {
    console.error(error);
    Message.error(error)
    return Promise.reject(error)
});

const httpDso = axios.create({
    baseURL: baseURL2,
    timeout: 3000,
    // headers: {'X-Custom-Header': 'foobar'},
    
    withCredentials: process.env.NODE_ENV === 'production'?true:false
});

httpDso.interceptors.request.use(config => {
    
    config.headers.Authorization = token();
    // var defaults = {
    //     '_t': new Date().getTime()
    // };
    // if (config.method === 'get') {
    //     if (isPlainObject(config.params)) {
    //         config.params = {
    //             ...defaults,
    //             ...config.params
    //         }
    //     }
    // } else if (config.method === 'post') {
    //     if (isPlainObject(config.data)) {
    //         config.data = {
    //             ...defaults,
    //             ...config.data
    //         }
    //     }
    //     if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
    //         config.data = qs.stringify(config.data)
    //     }
    // }
    return config
}, (error) => {
    return Promise.reject(error)
});

/**
 * 响应拦截
 */
httpDso.interceptors.response.use(response => {
    
    if (response.data && response.data.code === 401) { // 401, token失效
        console.warn("没有登录")
        editor.state.showLogin = true;
    } else if (response.data && response.data.code !== 0) {
        Message.warning(response.data.msg)
    }
    return response.data
},error => {
    console.log(error)
    console.error(error);
    Message.error(error)
    return Promise.reject(error)
});


const _aside_items = [
    { id: 5, text: '海报', icon: 'haibao', activated: false, extend: true ,badge:false},
    // {id: 1, text: '模板', icon: 'muban', activated: false, extend: true},
    { id: 2, text: '素材', icon: 'sucai', activated: false, extend: true ,badge:false},
    { id: 3, text: '组件', icon: 'zujian', activated: false, extend: true ,badge:false},
    { id: 4, text: '图层', icon: 'tuceng', activated: false, extend: true ,badge:false},
    { id: 6, text: '批量', icon: 'piliang1', activated: false, extend: true ,badge:true},
    // {
    //     id: 20,
    //     text: '帮助',
    //     icon: 'help1',
    //     activated: false,
    //     extend: false,
    //     type: 'link',
    //     link: 'https://fastposter.net/doc/'
    // },
    // {id: 11, text: '调试', icon: 'debug', activated: false, extend: false},
]

let loaded_font_map = {}

export default {
    baseURL,
    token,
    http,
    imgUrl(v) {
        return (v && !v.startsWith('http')) ? baseURL + v : v;
    },
    loadAsideItems(cb) {
        cb(_aside_items);
    },
    userinfo(playload, cb, err) {
        http.get('api/user').then(cb, err)
    },
    changepwd(playload, cb) {
        http.post('api/changepwd', playload).then(cb)
    },
    login(playload, cb) {
        // http.post('api/login', playload, {headers: {'content-type': 'application/x-www-form-urlencoded'}})
        http.post('api/login', playload).then(cb)
    },
    logout(playload, cb) {
        http.post('api/logout', playload).then(cb)
    },
    loadPosters(cb) {
        http.get('api/posters').then(cb)
    },
    loadBatchs(cb) {
        http.get('api/batchs').then(cb)
    },
    loadBatch(id, cb) {
        http.get(`api/batchs/${id}`).then(cb)
    },
    saveBatch(playload, cb) {
        http.post('api/batchs', playload).then(cb)
    },
    updatBatch(playload, cb) {
        http.put('api/batchs', playload).then(cb)
    },
    removeBatch(id, cb) {
        http.delete('api/batchs/' + id).then(cb)
    },
    loadMaterial(playload, cb) {
        http.get('api/materials', { params: playload }).then(cb)
    },
    removeMaterial(id, cb) {
        http.delete('api/materials/' + id).then(cb)
    },
    loadPoster(id, cb) {
        http.get('api/posters/' + id).then(cb)
    },
    savePoster(playload, cb) {
        http.post('api/posters', playload).then(cb)
    },
    updatePoster(playload, cb) {
        http.put('api/posters', playload).then(cb)
    },
    copyPoster(id, cb) {
        http.post(`api/posters/${id}/copy`).then(cb)
    },
    removePoster(id, cb) {
        http.delete('api/posters/' + id).then(cb)
    },
    previewPoster(playload, cb) {
        return new Promise((resolve) => {
            let xhr = new XMLHttpRequest();
            xhr.withCredentials = true;
            xhr.open("POST", baseURL + 'api/preview', true);
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.setRequestHeader("token", token());
            xhr.responseType = "blob";      // POST图片预览,必须使用此种方式才行
            xhr.onload = ({ currentTarget: r }) => {
                if (r.status === 200) {
                    let blob = r.response;
                    cb(blob)
                    resolve(blob)
                }
            };
            xhr.send(JSON.stringify(playload));
        })
    },
    queryTokenList(playload, cb) {
        return http.get('api/tokens', playload).then(cb)
    },
    updateToken(playload, cb) {
        return http.put('api/tokens', playload).then(cb)
    },
    loadfont(name) {
        if (!name || name in loaded_font_map) {
            // console.warn('font has loaded', name)
            return
        }
        loaded_font_map[name] = 1
        let url = baseURL + 'store/fonts/' + name;
        let style = document.createElement('style');
        style.innerText = '@font-face {font-family: "' + name + '"; src:url("' + url + '")}; font-display: swap;';
        document.getElementsByTagName('head')[0].appendChild(style);
    },
    reqUserPackagePayBuyList(playload, cb) {
        return httpDso.post('user/package/buyList', playload).then(cb)
    },
    reqUserPackageBuy(playload, cb) {
        return httpDso.post(`user/package/buy`, playload).then(cb)
    },
    // 示例数据
    postExampleData(playload, cb) {
        return httpDso.post(`KeywordDouyinSearch/exampleData`, playload).then(cb)
    },
    postUserCardExchange(playload, cb) {
        return httpDso.post(`user/cardExchange`, playload).then(cb)
    },
    reqUserPackageList(playload, cb) {
        return httpDso.get(`user/package/list`, playload).then(cb)
    },
    reqOvertPackageList(playload, cb) {
        return httpDso.get(`overt/packageList`, playload).then(cb)
    },
    reqResidueTimes(playload, cb) {
        return httpDso.post(`FastPosterToolGenerate/userPermission`, playload).then(cb)
    }



}

